package com.cqc.jdk8.Jlang.object;

/**
 * Object类有3个方法 wait(..)  notify()  notifyAll()，都 必须在 synchronized 修饰的代码内
 */
public class ObjectWaitNotifyTest {

    static boolean flag = false;
    static final Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                //while (!flag) {
                System.out.println(Thread.currentThread().getName() + "...t1...start...waiting...");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //}
                System.out.println(Thread.currentThread().getName() + "..t1...end..flag is " + flag);
            }
        });

        Thread t2 = new Thread(() -> {
            synchronized (lock) {
                //while (!flag) {
                System.out.println(Thread.currentThread().getName() + "..t2...start...waiting...");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //}
                System.out.println(Thread.currentThread().getName() + "..t2...end...flag is " + flag);
            }
        });

        Thread t3 = new Thread(() -> {
            synchronized (lock) {
                System.out.println(Thread.currentThread().getName() + "..t3...start");
                //lock.notifyAll();
                lock.notify();
                flag = true;
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "..t3 end");
            }
        });
/**
 * 为什么用flag?
 * 答：线程是随机执行的，如果没有flag变量，那么t1执行完，轮到t3执行，
 * t3执行完唤醒t1.此时时间片分给t2，
 * t2永远处在等待状态，那么jvm实例一直不会销毁
 * 下面的代码顺序可以 还原这种情况(去掉flag+notify()的情况下)
 *
 * 加了flag，t2才会结束，不会阻塞
 */
        t1.start();
        t2.start();
        t3.start();
    }

}
